package com.yz.jdd.webview;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.net.wifi.ScanResult;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;

import androidx.core.content.FileProvider;

import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import com.alipay.sdk.app.AuthTask;
import com.alipay.sdk.app.PayTask;
import com.gyf.barlibrary.ImmersionBar;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;

import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.DefaultHandler;
import com.google.gson.JsonParser;
import com.trello.rxlifecycle.ActivityEvent;
import com.google.gson.JsonObject;
import com.yunzong.permissions.OnPermission;
import com.yunzong.permissions.Permission;
import com.yunzong.permissions.XXPermissions;
import com.yunzong.wifi.WifiSupport;
import com.yunzong.wifi.netconfig.SmartConfig;
import com.yz.jdd.R;
import com.yz.jdd.base.MyApplication;
import com.yz.jdd.base.activity.BaseActivity;
import com.yz.jdd.base.activity.PhotoViewActivity;
import com.yz.jdd.base.entity.Image;
import com.yz.jdd.base.entity.Response_Base;
import com.yz.jdd.base.event.Events;
import com.yz.jdd.base.event.RxBus;
import com.yz.jdd.base.utils.AppUtils;
import com.yz.jdd.base.utils.AuthResult;
import com.yz.jdd.base.utils.FileUtils;
import com.yz.jdd.base.utils.ProviderUtil;
import com.yz.jdd.base.utils.StringUtil;
import com.yz.jdd.module.cashier.scanpay.ScanpayActivity;
import com.yz.jdd.module.help.HelpActivity;
import com.yz.jdd.module.launch.model.AppVersion;
import com.yz.jdd.module.scan.view.ScanActivity;
import com.yz.jdd.module.upgrade.DownLoadDialogActivity;
import com.yz.jdd.network.ApiCallback;
import com.yz.jdd.base.utils.BaseConfigs;
import com.yz.jdd.base.utils.Constants;
import com.yz.jdd.base.utils.GsonUtils;
import com.yz.jdd.base.utils.LogUtils;
import com.yz.jdd.base.utils.PreferencesUtils;
import com.yz.jdd.module.login.view.LoginActivity;
import com.yz.jdd.network.MySubscriber;
import com.yz.jdd.network.NetWorkRequset;
import com.yz.jdd.network.response.Response_upgrade;
import com.yz.jdd.photo.entity.Compress;
import com.yz.jdd.photo.entity.Crop;
import com.yz.jdd.photo.entity.MaxSize;
import com.yz.jdd.photo.entity.Photo;
import com.yz.jdd.photo.app.TakePhoto;
import com.yz.jdd.photo.app.TakePhotoImpl;
import com.yz.jdd.photo.compress.CompressOptions;
import com.yz.jdd.photo.model.CropOptions;
import com.yz.jdd.photo.model.InvokeParam;
import com.yz.jdd.photo.model.LubanOptions;
import com.yz.jdd.photo.model.TContextWrap;
import com.yz.jdd.photo.model.TImage;
import com.yz.jdd.photo.model.TResult;
import com.yz.jdd.photo.model.Upload;
import com.yz.jdd.photo.permission.InvokeListener;
import com.yz.jdd.photo.permission.PermissionManager;
import com.yz.jdd.photo.permission.TakePhotoInvocationHandler;
import com.yz.jdd.photo.utils.TConstant;
import com.yz.jdd.photo.utils.TImageFiles;
import com.yz.jdd.photo.utils.TUtils;
import com.yz.jdd.service.PlayerMusicService;
import com.yz.jdd.voice.OrderVoice;
import com.yz.jdd.voice.SpeechUtilOffline;
import com.yz.jdd.webview.download.DataCleanManager;
import com.yz.jdd.webview.download.FetchUtil;
import com.yz.jdd.webview.download.H5DownFileUtils;
import com.yz.jdd.webview.entity.PayResult;
import com.yz.jdd.webview.entity.UserInfo;
import com.yz.jdd.webview.net.H5Subscription;
import com.yz.jdd.widget.PublicDialog;
import com.yz.jdd.widget.TopDialog;


import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import rx.functions.Action1;

import static android.os.Environment.DIRECTORY_PICTURES;


/**
 * 项目名称：Maneki
 * 创建人：zx
 * 创建时间：2017/1/11-下午2:36
 * h5与java交互
 */

public class H5BridgeActivity extends BaseActivity implements TakePhoto.TakeResultListener, InvokeListener {
    public static final String TAG = "zx";
    private BridgeWebView webview; //webview
    private LinearLayout errorLayout;
    private Intent intent;
    private String main_url = "";//跳转到该页面的url 由上一个页面返回
    private String default_folder = "file://" + H5DownFileUtils._UPZIP_FOLDERPATH;
    private List<String> apiQueue = new ArrayList<String>();
    private TakePhoto takePhoto;
    private CallBackFunction takePictureCallBackFunction;
    private CallBackFunction selectPictureCallBackFunction;
    private CallBackFunction photoviewCallBackFunction;
    private CallBackFunction uploadPictureCallBackFunction;
    private CallBackFunction savePictureCallBackFunction;
    private CallBackFunction scanCallBackFunction;
    private CallBackFunction authV2CallBackFunction;//
    private CallBackFunction payV2CallBackFunction;
    private InvokeParam invokeParam;

    private static String apiName;

    private EditText editText;
    private Button button;
    private Button scan;
    LinearLayout loading_layout;
//    ImageView blinkImg;

    private boolean control;

    RelativeLayout top_bar;
    ImageView back;
    ImageView close_web;
    TextView title;
    TextView rightTextView;
    private static final int SDK_PAY_FLAG = 2;
    SmartConfig smartConfig;

    boolean showTopbar;

    private MyRecriver myRecriver;
    private IntentFilter intentFilter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
        ImmersionBar.with(this)
                .reset()  //重置所以沉浸式参数
                .transparentStatusBar()  //透明状态栏，不写默认透明色
                .statusBarColor(R.color.color_ffffff)     //状态栏颜色，不写默认透明色
                .statusBarDarkFont(true, 0.01f)   //状态栏字体是深色，不写默认为亮色
                .flymeOSStatusBarFontColor(R.color.color_333333)  //修改flyme OS状态栏字体颜色
                .fitsSystemWindows(true)    //解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色
                .supportActionBar(false) //支持ActionBar使用
                .addTag("tag")  //给以上设置的参数打标记
                .getTag("tag")  //根据tag获得沉浸式参数
                .init();
        setContentView(R.layout.activity_h5bridgeweb);
        AndroidBug5497Workaround.assistActivity(this);
        init();

        myRecriver = new MyRecriver();
        intentFilter = new IntentFilter();
        intentFilter.addAction("updateH5Page");
        registerReceiver(myRecriver, intentFilter);

    }

    /**
     * 注册RxBus事件监听
     */
    void registerRxBusEvents() {
        RxBus.with(H5BridgeActivity.this).setEvent(Events.EVENT_IMAGEPREVIEW_RESULT).setEndEvent(ActivityEvent.DESTROY).onNext(new Action1<Events<?>>() {
            @Override
            public void call(Events<?> events) {
                if (events != null) {
                    if (Events.EVENT_IMAGEPREVIEW_RESULT.equals(events.code)) {
                        Response_Base response_base = events.getContent();
                        if (response_base != null) {
                            HostJsScope.h5PostLocalCallBack(webview, response_base.getCode(), response_base.getMsg(), response_base.success(), "viewPicture", response_base, photoviewCallBackFunction);
                            if (photoviewCallBackFunction != null) {
                                photoviewCallBackFunction = null;
                            }
                        }
                    }

                }
            }
        }).create();
        /**
         * 上传图回调h5
         */
        RxBus.with(H5BridgeActivity.this).setEvent(Events.EVENT_UPLOADPICTURE_RESULT).setEndEvent(ActivityEvent.DESTROY).onNext(new Action1<Events<?>>() {
            @Override
            public void call(Events<?> events) {
                if (events != null) {
                    if (Events.EVENT_UPLOADPICTURE_RESULT.equals(events.code)) {
                        String str = events.getContent();
                        LogUtils.d("str :: " + str);
                        if (!TextUtils.isEmpty(str)) {
                            try {

                                JsonObject returnData = new JsonParser().parse(str).getAsJsonObject();
                                if (returnData != null) {
                                    HostJsScope.h5PostLocalCallBack(webview, "0", "图片上传成功", true, "uploadPicture", returnData, uploadPictureCallBackFunction);
                                    Log.e("lkf", "------uploadPictureCallBackFunction");
                                    if (uploadPictureCallBackFunction != null) {
                                        uploadPictureCallBackFunction = null;
                                    }
                                } else {
                                    Log.e("lkf", "------returnData==null");
                                    HostJsScope.h5PostLocalCallBack(webview, "-1", "图片上传失败", false, "uploadPicture", str, uploadPictureCallBackFunction);
                                    Log.e("lkf", "------uploadPictureCallBackFunction");

                                    if (uploadPictureCallBackFunction != null) {
                                        uploadPictureCallBackFunction = null;
                                    }
                                }
                            } catch (Exception e) {
                                Log.e("lkf", "------returnData==null");
                                HostJsScope.h5PostLocalCallBack(webview, "-1", "图片上传失败", false, "uploadPicture", str, uploadPictureCallBackFunction);
                                Log.e("lkf", "------Exception==" + e.toString());

                                if (uploadPictureCallBackFunction != null) {
                                    uploadPictureCallBackFunction = null;
                                }
                            }
                        } else {
                            HostJsScope.h5PostLocalCallBack(webview, "-1", "图片格式不支持", false, "uploadPicture", str, uploadPictureCallBackFunction);
                            if (uploadPictureCallBackFunction != null) {
                                uploadPictureCallBackFunction = null;
                            }
                        }
                    }

                }
            }
        }).create();

//        RxBus.with(H5BridgeActivity.this).setEvent(Events.EVENT_LOAD_URL).setEndEvent(ActivityEvent.DESTROY).onNext(new Action1<Events<?>>() {
//            @Override
//            public void call(Events<?> events) {
//                Log.i("lkf", "event_load_url");
//                if (events != null) {
//                    dismissLoading();
//                    webview.loadUrl(main_url);
//                }
//            }
//        }).create();
//        //注册一个语音播报通知
//        RxBus.with(H5BridgeActivity.this).setEvent(Events.EVENT_VOICE_BROADCAT).setEndEvent(ActivityEvent.DESTROY).onNext(new Action1<Events<?>>() {
//            @Override
//            public void call(Events<?> events) {
//                Log.i("lkf", "H5BridgeActivity+EVENT_VOICE_BROADCAT");
//                if (events != null) {
//                    Log.i("lkf", "H5BridgeActivity+EVENT_VOICE_BROADCAT");
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            webview.loadUrl("javascript:AppUtil.trigger(AppUtil.EVENTS.NEW_ORDER_EVENT);");
//                        }
//                    });
//
//                }
//            }
//        }).create();
    }

    // 多进程,广播接收消息
    class MyRecriver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String content = intent.getStringExtra("event");
            if (!StringUtil.isEmpty(content)) {
                if (Events.EVENT_VOICE_BROADCAT.equals(content)) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            webview.loadUrl("javascript:AppUtil.trigger(AppUtil.EVENTS.NEW_ORDER_EVENT);");
                        }
                    });
                }
            } else {
                if (Events.EVENT_LOAD_URL.equals(content)) {
//                LogBackUtil.i("lkf"+ "event_load_url");
                    dismissLoading();
                    webview.loadUrl(main_url);
                }
            }

        }
    }


    private void init() {
        String sessionId = getIntent().getStringExtra("sessionId");
        if (!PreferencesUtils.getString(H5BridgeActivity.this, BaseConfigs.PREF_SESSIONID, "").equals(sessionId)) {
            if (!TextUtils.isEmpty(sessionId)) {
                PreferencesUtils.putString(H5BridgeActivity.this, BaseConfigs.PREF_SESSIONID, sessionId);
            }

        }

        loading_layout = (LinearLayout) findViewById(R.id.loading_layout);
//        blinkImg = (ImageView) findViewById(R.id.blinkImg);

        String loading = getIntent().getStringExtra("loading");
        if (!TextUtils.isEmpty(loading)) {
            loading_layout.setVisibility(View.GONE);
        }

        editText = (EditText) findViewById(R.id.edittext);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!TextUtils.isEmpty(editText.getText().toString())) {
                    webview.loadUrl(editText.getText().toString() + "?android=4.1&statusBarHeight=40");
                }
            }
        });
        scan = (Button) findViewById(R.id.scan);
        scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(H5BridgeActivity.this, ScanActivity.class));
            }
        });
        top_bar = (RelativeLayout) findViewById(R.id.top_bar);
        back = (ImageView) findViewById(R.id.back);
        /**
         * 注册事件
         */
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (control) {
                    webview.loadUrl("javascript:AppUtil.trigger(AppUtil.EVENTS.BACK_EVENT);");
                } else {
                    if (webview.canGoBack()) {
                        webview.goBack();
                    } else {
                        finish();
                    }
                }

            }
        });
        close_web = findViewById(R.id.close_web);
        close_web.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        title = (TextView) findViewById(R.id.title);


        rightTextView = (TextView) findViewById(R.id.right);


        registerRxBusEvents();
        webview = (BridgeWebView) findViewById(R.id.webview);
        errorLayout = (LinearLayout) findViewById(R.id.error_layout);
        errorLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isErrorPage = false;

                webview.reload();
            }
        });
        intent = this.getIntent();
        main_url = intent.getStringExtra(Constants.H5_WEB_URL);
        Log.e("lkf", "h5 main_url==" + main_url);
        showTopbar = intent.getBooleanExtra("intent", false);
        if (showTopbar) {
            top_bar.setVisibility(View.VISIBLE);
        }
        //main_url = "file:///android_asset/demo.html";
        //main_url="http://10.200.36.57:8080/cross-bh5/html/weixin_open_step2.html";

        initWebView();

    }

    private TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(H5BridgeActivity.this, this));
        }
        return takePhoto;
    }

    @Override
    protected void onResume() {
        super.onResume();
        //界面被唤醒的时候调用
        Log.i("zx", "onResume");
        webview.loadUrl("javascript:AppUtil.trigger(AppUtil.EVENTS.RESUME_EVENT);");
        stopService(new Intent(this, PlayerMusicService.class));
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && !isErrorPage) {
            //返回键调用js方法
            if (control) {
                webview.loadUrl("javascript:AppUtil.trigger(AppUtil.EVENTS.BACK_EVENT);");
            } else {
                if (webview.canGoBack()) {
                    webview.goBack();
                } else {
                    finish();
                }
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //webview.reload();
        if (intent != null) {
            String url = intent.getStringExtra(Constants.H5_WEB_URL);
            if (!TextUtils.isEmpty(url)) {
                webview.loadUrl(url);
                Log.e("lirui", "onNewIntent:url== " + url);
            }
        }
    }

    private void initWebView() {
        /**
         * 规则在定义请求接口的时候需要首先调用,apiQueue.add("getrequest"); 因为js会首先调用checkApi接口
         * 检验Android本地方法是否存在
         */
        apiQueue.add("takePicture");//拍照裁剪接口
        apiQueue.add("selectPicture");//选择图片裁剪接口
        apiQueue.add("viewPicture");//图片预览接口
        apiQueue.add("uploadPicture");//上传图片
        apiQueue.add("logout");//退出登录接口
        apiQueue.add("getUserInfo");//获取用户信息
        apiQueue.add("exitApp");//js调用客户端前台切换到后台运行
        apiQueue.add("sendHttpRequest"); //发送http请求
        apiQueue.add("dial");//拨打电话
        apiQueue.add("login");//跳转登录

        apiQueue.add("setTitle");//设置页面的标题栏，包括主标题，副标题以及标题菜单项
        apiQueue.add("setOptionMenu");//设置标题栏右边的按钮属性。该接口仅负责设置，需要额外调用showOptionMenu保证该按钮的显示

        apiQueue.add("showOptionMenu");//显示标题栏右边的按钮属性
        apiQueue.add("hideOptionMenu");//隐藏标题栏右边的按钮属性

        apiQueue.add("pushWindow");//用来打开一个新的页面，系统自带转场动画。
        //与location.href的区别，类同于PC浏览器的新开标签页，每个window都是一个新的标签页，因此原页面仅仅是被压到后台，状态始终保持，JS也会继续运行。

        apiQueue.add("popWindow");//popWindow用来关闭当前页面，自动返回到上一个

        apiQueue.add("setBackOption");
        apiQueue.add("openApp");//打开三方app
        apiQueue.add("testVoiceBroadcast");
        apiQueue.add("savePicture");
        apiQueue.add("scan");
        apiQueue.add("authV2");//调用支付宝授权

        apiQueue.add("tradePay");//支付宝支付

        apiQueue.add("getNearbyWIFI");//1.获取附近wifi
        apiQueue.add("startBroadcast");//2.开启广播
        apiQueue.add("stopBroadcast");//3.关闭广播


        apiQueue.add("getAppVersion");//获取当前app版本号
        apiQueue.add("upgradeApp");//更新app版本

        apiQueue.add("openDetectVoiceRight");//语音播报故障诊断

        apiQueue.add("updateNativePage");//发消息给本地页面

        apiQueue.add("setServerUrl");//设置服务地址
        apiQueue.add("removeH5Source");//删除H5资源
        apiQueue.add("resetAll");//重置所有
        apiQueue.add("downLoadH5Source");//下载H5资源
        apiQueue.add("hideSplash");//隐藏

        apiQueue.add("writeLogToApp");//写日志接口

        apiQueue.add("openWifi");//打开wifi
        apiQueue.add("shardBySystem");

        // 设置具体WebViewClient
        webview.setWebViewClient(new MyWebViewClient(webview));
        webview.setWebChromeClient(new WebChromeClient() {

//            @Override
//            public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
//
//                //do something
//
//                return true;
//                //return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
//            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                Log.i(TAG, "onProgressChanged:----------->" + newProgress);
                if (newProgress == 100) {
//                    loadingLayout.setVisibility(View.GONE);
                }
            }


            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                Log.i(TAG, "onReceivedTitle:title ------>" + title);
                String substring = "404";
                int index = title.indexOf('#');  // 找到#的位置
                if (index != -1) {
                    String substringBeforeHash = title.substring(0, index);
                    if (substringBeforeHash.contains(substring)) {
                        showErrorPage();
                    }
                }
            }
        });
        webview.getSettings().setAllowFileAccess(true);
        webview.getSettings().setAllowFileAccessFromFileURLs(true);
        webview.getSettings().setAllowUniversalAccessFromFileURLs(true);
        webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webview.getSettings().setDefaultTextEncodingName("utf-8");
//        webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
//        webview.setLayerType(View.LAYER_TYPE_HARDWARE, null);

        //极速云所需配置
        webview.getSettings().setDomStorageEnabled(true);
        webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);//支持js调用window.open方法
        webview.getSettings().setSupportMultipleWindows(false);// 设置允许开启多窗口
        String ua = webview.getSettings().getUserAgentString();
        webview.getSettings().setUserAgentString(ua + ";androidapp/cross-bmios" + ";webJSY/1.0.0");

        //webview.loadUrl(main_url);
//        webview.getSettings().setUseWideViewPort(true);
        webview.getSettings().setRenderPriority(WebSettings.RenderPriority.LOW);
        webview.getSettings().setTextSize(WebSettings.TextSize.NORMAL);

        webview.getSettings().setTextZoom(100);


//        if (PreferencesUtils.getBoolean(this, BaseConfigs.BOOLEAN_H5MODULE)) {
//            Log.i("lkf", "event_load_url");
        webview.loadUrl(main_url);
//        } else {
//
//        }
/**
 * 调用系统分享
 */
        webview.registerHandler("shardBySystem", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (TextUtils.isEmpty(data)) {
                    return;
                }
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                String filePath = Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES) + "" + "/yz" + System.currentTimeMillis() + ".jpg";
                File takeImageFile = new File(filePath);
                if (jsonObject != null && jsonObject.get("imageBase64Str") != null) {
                    String imageBase64Str = jsonObject.get("imageBase64Str").getAsString();
                    Log.e("lkf", imageBase64Str);
                    int index = imageBase64Str.indexOf(",");
                    String subStr = imageBase64Str.substring(index + 1);
                    Log.e("lkf", subStr);
                    try {
                        byte[] buffer = Base64.decode(subStr.getBytes(), Base64.DEFAULT);
                        FileOutputStream out = new FileOutputStream(takeImageFile);
                        out.write(buffer);
                        out.close();
                        Log.e("lkf", takeImageFile.length() + "");
                    } catch (Exception e) {
                        Log.e("lkf", e.toString());
                        e.printStackTrace();
                    }

                }

                Uri uri;
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
                    uri = Uri.fromFile(takeImageFile);
                } else {
                    /**
                     * 7.0 调用系统相机拍照不再允许使用Uri方式，应该替换为FileProvider
                     * 并且这样可以解决MIUI系统上拍照返回size为0的情况
                     */
                    uri = FileProvider.getUriForFile(H5BridgeActivity.this, ProviderUtil.getFileProviderName(H5BridgeActivity.this), takeImageFile);
                }


                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_SEND);

                intent.putExtra(Intent.EXTRA_STREAM, uri);
//                intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
                intent.setType("image/*");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

                startActivity(Intent.createChooser(intent, ""));
            }
        });

        /**
         * 打开wifi
         */
        webview.registerHandler("openWifi", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Intent wifiSettingsIntent = new Intent("android.settings.WIFI_SETTINGS");
                startActivity(wifiSettingsIntent);
            }
        });
        /**
         * 隐藏
         */
        webview.registerHandler("hideSplash", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                loading_layout.setVisibility(View.GONE);
//                blinkImg.
            }
        });
        webview.registerHandler("writeLogToApp", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (TextUtils.isEmpty(data)) {
                    return;
                }
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("text") != null) {
                    String text = jsonObject.get("text").getAsString() + "";

                }

            }
        });


        /**
         * 发消息给本地页面
         */
        webview.registerHandler("updateNativePage", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                LogUtils.i("ljm--- H5 " + data);  //
                //追加入参{page:“orderPage”}       homePage表示首页   orderPage表示订单页   newsPage表示toolbar上消息页面刷新数据
                Intent intent = new Intent("updateNativePage");
                if (data.contains("newsPage")) {
                    //     RxBus.getInstance().send(Events.EVENT_BACKLOG_CHANGE, "");
                    intent.putExtra("page", "newsPage");
                    sendBroadcast(intent);
                } else {
                    if (data.contains("orderPage")) {
                        //发消息,刷新首页/列表数据
                        intent.putExtra("page", "orderPage");
                        sendBroadcast(intent);
                    }
                }

            }
        });

        /**
         * 设置服务地址url,清除版本号，删除资源，重启
         */
        webview.registerHandler("setServerUrl", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
//                Log.e("lkf", data + "");
                if (TextUtils.isEmpty(data)) {
                    return;
                }
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("url") != null) {
                    String url = jsonObject.get("url").getAsString() + "";
                    if (!TextUtils.isEmpty(url)) {
                        DataCleanManager.cleanApplicationData(H5BridgeActivity.this);
                        PreferencesUtils.putString(
                                H5BridgeActivity.this, BaseConfigs.STRING_SERVER_URL, url);
                        PreferencesUtils.putString(
                                H5BridgeActivity.this, BaseConfigs.STRING_GUID, "");

                        Log.e("lkf", url);
                        //删除资源
                        android.os.Process.killProcess(android.os.Process.myPid());


                    }

                }

            }
        });

        /**
         * 删除H5资源,删除解压文件
         */
        webview.registerHandler("removeH5Source", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                DataCleanManager.cleanApplicationData(H5BridgeActivity.this);
                android.os.Process.killProcess(android.os.Process.myPid());

            }
        });

        /**
         * 重置所有,删除data
         */
        webview.registerHandler("resetAll", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                DataCleanManager.cleanApplicationData(H5BridgeActivity.this);
                android.os.Process.killProcess(android.os.Process.myPid());


            }
        });

        /**
         * 下载解压H5资源
         */
        webview.registerHandler("downLoadH5Source", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (TextUtils.isEmpty(data)) {
                    return;
                }
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("url") != null) {
                    String downLoadUrl = jsonObject.get("url").getAsString() + "";
                    if (!TextUtils.isEmpty(downLoadUrl)) {

                        FetchUtil.downLoadH5zip(downLoadUrl);

                    }
                }

            }
        });

        //////////////////////////////////////////////////跳转登录关闭其他页面
        webview.registerHandler("login", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                RxBus.getInstance().send(Events.EVENT_302CODE, "");
                Intent intent = new Intent(H5BridgeActivity.this, LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.putExtra("logout", "1");
                startActivity(intent);

            }
        });
        webview.registerHandler("openDetectVoiceRight", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

                Intent intent = new Intent(H5BridgeActivity.this, HelpActivity.class);

                startActivity(intent);

            }
        });

        /**
         * 获取附近wifi
         */
        webview.registerHandler("getNearbyWIFI", new BridgeHandler() {
            @Override
            public void handler(String data, final CallBackFunction function) {
                XXPermissions.with(H5BridgeActivity.this).permission(
                        Permission.ACCESS_COARSE_LOCATION,
                        Permission.ACCESS_FINE_LOCATION
                ).request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        if (isAll) {
                            dismissTopDialog();
                            Log.e("lkf", "------");
                            if (WifiSupport.isOpenWifi(H5BridgeActivity.this)) {
                                List<ScanResult> scanResults = WifiSupport.noSameName(WifiSupport.getWifiScanResult(H5BridgeActivity.this));
                                if (scanResults != null) {
                                    List<String> wifiList = new ArrayList<>();
                                    for (ScanResult scanResult : scanResults) {
                                        wifiList.add(scanResult.SSID);
                                    }
                                    if (wifiList.size() > 0) {
                                        HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_SUCCESS,
                                                "", true, "getNearbyWIFI", wifiList, function);
                                    } else {
                                        HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL,
                                                "未取到wif信息", false, "getNearbyWIFI", null, function);
                                    }

                                }

                            } else {
                                final PublicDialog publicDialog = new PublicDialog(H5BridgeActivity.this);
                                publicDialog.setMessage("请先开启手机Wi-Fi功能");
                                publicDialog.setRightBtn("去开启",
                                        new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS)); //直接进入手机中的wifi网络设置界面
                                                publicDialog.dismiss();
                                            }
                                        });
                                publicDialog.show();
                            }
                        }


                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        dismissTopDialog();
                        HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL,
                                "未开启wifi权限", false, "getNearbyWIFI", null, function);

                    }
                });
                if (!XXPermissions.isHasPermission(H5BridgeActivity.this, Permission.ACCESS_COARSE_LOCATION, Permission.ACCESS_FINE_LOCATION)) {
                    showTopDialog("为了您能正常使用玛卡龙、快小盒相关功能，请向您申请【定位】功能以获取附近WIFI，完成配网工作，保证功能的正常使用！");
                }

            }
        });
        /**
         * 2.开启广播
         */
        webview.registerHandler("startBroadcast", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
//                入参：type：”setUpNetwork"
//                content："{"name":"YUNZONG","password":"YUNZONGNET@WIFI”}"
                if (TextUtils.isEmpty(data)) {
                    return;
                }


                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);

//                {"type":"setUpNetwork","content":"{\"name\":\"YUNZONG\",\"password\":\"YUNZONGNET@WIFI”}"}
                if (jsonObject != null && jsonObject.get("content") != null) {
                    Log.e("lkf", "---1111content11111---");

                    String contentString = jsonObject.get("content").getAsString();
//                    Log.e("lkf", "---contentString---" + contentString);
                    if (!TextUtils.isEmpty(contentString)) {
                        JsonObject content = HostJsScope.Json2JsonObject(contentString);
                        String name = content.get("name").getAsString() + "";
                        String password = content.get("password").getAsString() + "";
                        if (smartConfig != null) {
                            smartConfig.stop();
                        }
                        smartConfig = new SmartConfig(H5BridgeActivity.this);
                        smartConfig.start(name, password);
//                        Log.e("lkf", "---password---");


                    }

                }


            }
        });
        /**
         * //3.关闭广播
         */
        webview.registerHandler("stopBroadcast", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (smartConfig != null) {
                    smartConfig.stop();
                }
            }
        });


        webview.registerHandler("openApp", new DefaultHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (TextUtils.isEmpty(data)) {
                    return;
                }
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("url") != null) {
                    String url = jsonObject.get("url").getAsString() + "";

                    Response_Base response_base = new Response_Base();
                    response_base.setResultObject(null);
                    if (url.startsWith("alipays:") || url.startsWith("alipay")) {
                        try {
                            startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                            response_base.setCode("0");
                            response_base.setSuccess(true);
                            HostJsScope.h5PostLocalCallBack(webview, "0", "", true, "openApp", response_base, function);
                        } catch (Exception e) {

                            response_base.setCode("-1");
                            response_base.setSuccess(false);
                            HostJsScope.h5PostLocalCallBack(webview, "-1", "", true, "openApp", response_base, function);
                        }

                    }

                }

            }
        });

        /**
         * 控制返回事件
         */
        webview.registerHandler("setBackOption", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("control") != null) {
                    control = jsonObject.get("control").getAsBoolean();
                }
            }
        });

        /**
         * 设置页面的标题栏，包括主标题，副标题以及标题菜单项
         * background：”#ff0000”,   //标题栏背景色 color：”#ffff00”//文字颜色
         */
        webview.registerHandler("setTitle", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (TextUtils.isEmpty(data)) {
                    return;
                }
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("title") != null) {
                    String titleStr = jsonObject.get("title").getAsString() + "";
                    title.setText(titleStr);
                }
                if (jsonObject != null && jsonObject.get("background") != null) {
                    String colorStr = jsonObject.get("background").getAsString() + "";
                    top_bar.setBackgroundColor(Color.parseColor(colorStr));
                }
                if (jsonObject != null && jsonObject.get("color") != null) {
                    String titleColorStr = jsonObject.get("color").getAsString() + "";
                    title.setTextColor(Color.parseColor(titleColorStr));

                }
                if (jsonObject != null && jsonObject.get("showClose") != null) {
                    boolean showClose = jsonObject.get("showClose").getAsBoolean();
                    if (showClose) {
                        close_web.setVisibility(View.VISIBLE);
                    } else {
                        close_web.setVisibility(View.GONE);
                    }
                }
            }
        });
        /**
         * 设置标题栏右边的按钮属性。该接口仅负责设置，需要额外调用showOptionMenu保证该按钮的显示
         * {title : '按钮',color : '#ff00ff00', // 必须以＃开始ARGB颜色值}
         */
        webview.registerHandler("setOptionMenu", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                if (TextUtils.isEmpty(data)) {
                    return;
                }
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("title") != null) {
                    String rightBtnStr = jsonObject.get("title").getAsString() + "";
                    rightTextView.setText(rightBtnStr);
                }
                if (jsonObject != null && jsonObject.get("color") != null) {
                    String rightBtnColor = jsonObject.get("color").getAsString() + "";
                    rightTextView.setTextColor(Color.parseColor(rightBtnColor));
                }
            }
        });
        /**
         * 显示标题栏右边的按钮属性
         */
        webview.registerHandler("showOptionMenu", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                rightTextView.setVisibility(View.VISIBLE);
            }
        });
        /**
         * 隐藏标题栏右边的按钮属性
         */
        webview.registerHandler("hideOptionMenu", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                rightTextView.setVisibility(View.GONE);
            }
        });

        /**
         * 测试语音
         */
        webview.registerHandler("testVoiceBroadcast", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                try {
                    JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                    if (jsonObject != null && jsonObject.get("text") != null) {
                        String text = jsonObject.get("text").getAsString() + "";
                        OrderVoice orderVoice = new OrderVoice();
                        orderVoice.setContent(text);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    OrderVoice orderVoice = new OrderVoice();
                    orderVoice.setContent("语音播报成功");
                    if (XXPermissions.isHasPermission(H5BridgeActivity.this, Permission.READ_PHONE_STATE)) {
                        try {
                            LogUtils.e("===  play Content:" + orderVoice.getContent());
                            SpeechUtilOffline.getInstance(MyApplication.application).play(orderVoice, SpeechUtilOffline.PLAY_MODE.QUEUED);
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                    }
                }


            }
        });

        /**
         * //用来打开一个新的页面，系统自带转场动画。
         * 与location.href的区别，类同于PC浏览器的新开标签页，每个window都是一个新的标签页，
         * 因此原页面仅仅是被压到后台，状态始终保持，JS也会继续运行。
         * {
         url: 'https://m.taobao.com/',
         param: {
         title: {
         title: '标题’,
         background：”#ff0000”,   //标题栏背景色
         color：”#ffff00”         //标题栏前景色
         },
         showOptionMenu: false  //缺省  可不传，默认为false
         }

         */
        webview.registerHandler("pushWindow", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                LogUtils.e(data);
                if (TextUtils.isEmpty(data)) {
                    return;
                }
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null) {
                    Intent intent = new Intent(H5BridgeActivity.this, H5BridgeOtherActivity.class);

                    if (jsonObject.get("param") != null) {
                        JsonObject paramJsonObject = (JsonObject) jsonObject.get("param");
                        if (paramJsonObject != null) {
                            try {
                                JsonObject titleJsonObject = (JsonObject) paramJsonObject.get("title");
                                if (titleJsonObject != null) {
                                    String titleStr = titleJsonObject.get("title").getAsString() + "";
                                    if (!TextUtils.isEmpty(titleStr)) {
                                        intent.putExtra("title", titleStr);
                                    }
                                    String backgroundStr = titleJsonObject.get("background").getAsString() + "";
                                    if (!TextUtils.isEmpty(backgroundStr)) {
                                        intent.putExtra("background", backgroundStr);
                                    }

                                    String colorStr = titleJsonObject.get("color").getAsString() + "";
                                    if (!TextUtils.isEmpty(colorStr)) {
                                        intent.putExtra("color", colorStr);
                                    }
                                } else {
                                    intent.putExtra("showTop", "showTop");
                                }
                            } catch (Exception e) {
                                Log.e("lkf", e.toString());
                                intent.putExtra("showTop", "showTop");
                            }
                        }

                    }
                    String parme = "";
                    if (jsonObject.get("suffixParams") != null) {
                        parme = jsonObject.get("suffixParams").getAsString() + "";
                    }
                    if (jsonObject.get("url") != null) {
                        String openUrl = jsonObject.get("url").getAsString() + "";
                        if (!TextUtils.isEmpty(openUrl)) {
                            String target = "";
                            if (jsonObject.get("target") != null) {
                                target = jsonObject.get("target").getAsString() + "";
                            }
//                        target: 'local',//local或者server

                            if ("local".equals(target)) {
                                openUrl = "file://" + H5DownFileUtils._UPZIP_FOLDERPATH + openUrl + "?s=" +
                                        PreferencesUtils.getString(H5BridgeActivity.this, BaseConfigs.PREF_SESSIONID) +
                                        "&statusBarHeight=0&android=4.1" + "&SDK=" + Build.VERSION.SDK_INT + parme
                                        + "&url=" + PreferencesUtils.getString(H5BridgeActivity.this, BaseConfigs.STRING_SERVER_URL, Constants.SERVER_URL);


                            }
                            if (!TextUtils.isEmpty(parme)) {
                                openUrl = openUrl + "&" + parme;
                            }
                            intent.putExtra(Constants.H5_WEB_URL, openUrl);

                            String sessionId = PreferencesUtils.getString(H5BridgeActivity.this, BaseConfigs.PREF_SESSIONID);
                            intent.putExtra("sessionId", sessionId);
                            startActivity(intent);
                        }

                    }

                }
            }
        });


        apiQueue.add("popWindow");
        /**
         * //popWindow用来关闭当前页面，自动返回到上一个
         */
        webview.registerHandler("popWindow", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                finish();
            }
        });
        //获取当前app版本号
        webview.registerHandler("getAppVersion", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                HostJsScope.h5PostLocalCallBack(webview, "0", "", true, "getAppVersion", AppUtils.getVerName(H5BridgeActivity.this), function);
            }
        });
        //更新app版本
        webview.registerHandler("upgradeApp", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Response_upgrade response_upgrade = (Response_upgrade) GsonUtils.json2Obj(data, Response_upgrade.class);
                Log.e("data", data);
                if (response_upgrade != null && response_upgrade.getAppVersion() != null) {
                    AppVersion appVersion = response_upgrade.getAppVersion();
                    String downLoadUrl = appVersion.getAddress();
                    showVersionUpdate(appVersion, downLoadUrl);
                }
            }
        });


        //--------------检验接口是否存在-------------------------------------------
        webview.registerHandler("checkApi", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                Response_Base response_base = new Response_Base();
                String code = "";
                String msg = "";
                boolean success;
                if (jsonObject != null && jsonObject.get("apiName") != null) {
                    String str = jsonObject.get("apiName").getAsString();
                    Log.i("zx", "str:" + str);
                    if (!TextUtils.isEmpty(str) && apiQueue.contains(str)) {
                        //说明接口存在
                        code = "0";
                        msg = "支持该接口";
                        success = true;

                    } else {
                        //接口不存在
                        code = "-1";
                        msg = "接口不存在";
                        success = false;
                    }
                } else {
                    //data格式有问题
                    code = "-1";
                    msg = "数据格式有问题";
                    success = false;
                }
                response_base.setResultObject(null);
                HostJsScope.h5PostLocalCallBack(webview, code, msg, success, "checkApi", response_base, function);

            }
        });
        ////////////////////////////////
        webview.registerHandler("dial", new DefaultHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (TextUtils.isEmpty(data)) {
                    return;
                }
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("mobile") != null) {
                    try {
                        String str = jsonObject.get("mobile").getAsString() + "";
                        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        Response_Base response_base = new Response_Base();
                        response_base.setCode("0");
                        response_base.setSuccess(true);
                        response_base.setResultObject(null);
                        HostJsScope.h5PostLocalCallBack(webview, "0", "", true, "dial", response_base, function);
                    } catch (Exception e) {
                        Toast.makeText(H5BridgeActivity.this, "暂不支持", Toast.LENGTH_SHORT).show();
                    }
                }

            }
        });
        //////////////////////////////////////////////////发送http请求
        webview.registerHandler("sendHttpRequest", new DefaultHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                HostJsScope jsScope = new HostJsScope();
                jsScope.resultCallBack(webview, "sendHttpRequest", data, function);
            }
        });
///////////////////////////////////////////////////////////////////切换app到后台
        webview.registerHandler("exitApp", new DefaultHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addCategory(Intent.CATEGORY_HOME);
                startActivity(intent);
            }
        });
        ///////////////////////////////////////////////////////
        webview.registerHandler("getUserInfo", new DefaultHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //Toast.makeText(H5BridgeActivity.this, data, Toast.LENGTH_SHORT).show();
                Response_Base response_base = new Response_Base();
                String code = "0";
                String msg = "获取用户信息";
                boolean success = true;
                UserInfo userInfo = new UserInfo();
                userInfo.setSessionId(PreferencesUtils.getString(H5BridgeActivity.this, BaseConfigs.PREF_SESSIONID));
                HostJsScope.h5PostLocalCallBack(webview, code, msg, success, "getUserInfo", userInfo, function);

            }
        });
/////////////////////退出登录///////////////////////////////////////////////

        webview.registerHandler("logout", new BridgeHandler() {
            @Override
            public void handler(String data, final CallBackFunction function) {
                H5Subscription.h5LogoutSubscription(new ApiCallback() {
                    @Override
                    public void onSuccess(Response_Base response_baseModel) {
                        PreferencesUtils.putString(H5BridgeActivity.this, BaseConfigs.STRING_MOVEKOUBEI, "0");
                        RxBus.getInstance().send(Events.EVENT_302CODE, "");
                        Intent intent = new Intent(H5BridgeActivity.this, LoginActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.putExtra("logout", "1");
                        startActivity(intent);
                        Response_Base response_base = new Response_Base();
                        response_base.setCode("0");
                        response_base.setSuccess(true);
                        response_base.setResultObject(null);
                        HostJsScope.h5PostLocalCallBack(webview, "0", "", true, "logout", response_base, function);

                    }

                    @Override
                    public void onNeedLogin(String msg) {
                        //IntentHandler.startLoginActivity(webView.getContext());

                    }

                    @Override
                    public void onFail(Response_Base response_baseModel) {
                        if (response_baseModel != null) {
                            String msg = response_baseModel.getMsg();
//                            if (!TextUtils.isEmpty(msg))
//                                Tools.showToast(H5BridgeActivity.this, msg);

                            HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL, "失败", true, "logout", "", function);
                        }
                    }
                });

            }
        });


        /**
         * 拍照并裁切接口
         *
         */
        webview.registerHandler("takePicture", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                LogUtils.d("---- h5 takePicture");

                Photo photo = (Photo) GsonUtils.json2Obj(data, Photo.class);
                TakePhoto takePhoto = getTakePhoto();
                if (photo != null) {
                    Compress compress = photo.getCompress();
                    MaxSize maxSize = photo.getMaxSize();
                    if (compress != null || maxSize != null) {
//                        Log.e("lkf", compress.getSizeLimit() + " unit:" + compress.getUnit());

                        LubanOptions.Builder builder = new LubanOptions.Builder();

                        if (maxSize != null) {
                            if (!TextUtils.isEmpty(maxSize.getWidth()) && !TextUtils.isEmpty(maxSize.getHeight())) {

                                builder.setMaxWidth(Integer.parseInt(maxSize.getWidth()))
                                        .setMaxHeight(Integer.parseInt(maxSize.getHeight()));
                            }
                        }
                        if (compress != null) {
                            builder.setMaxSize(compress.getSizeLimit() * 1024).setUnit(compress.getUnit());
                        }
                        LubanOptions compressOptions = builder.create();

                        CompressOptions config = CompressOptions.ofLuban(compressOptions);
                        config.enablePixelCompress(true);

                        takePhoto.onEnableCompress(config, true);
                    } else {
                        takePhoto.onEnableCompress(null, false);
                    }

                    Crop crop = photo.getCrop();
                    if (crop != null) {
                        CropOptions.Builder cropBuilder = new CropOptions.Builder();
                        CropOptions cropOptions = cropBuilder.setAspectX(crop.getWidthRatio()).setAspectY(crop.getHeightRatio()).setFormat(photo.getFormat()).create();
                        LogUtils.d(" crop one picture with width: " + crop.getWidthRatio() + " height:" + crop.getHeightRatio() + " format:" + photo.getFormat());
                        takePhoto.onPickFromCaptureWithCrop(TImageFiles.getTempFileUri(), cropOptions);
                    } else {
                        takePhoto.onPickFromCapture(TImageFiles.getTempFileUri());
                    }

                }
                apiName = "takePicture";
                takePictureCallBackFunction = function;

            }
        });
        /**
         * 选择多图接口 多图不支持裁剪 单图支持裁剪
         * selectPicture
         */
        webview.registerHandler("selectPicture", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                Uri imageUri = Uri.fromFile(file);
                Photo photo = (Photo) GsonUtils.json2Obj(data, Photo.class);
                if (photo != null) {

                    Compress compress = photo.getCompress();
                    MaxSize maxSize = photo.getMaxSize();
                    if (compress != null || maxSize != null) {
//                        LubanOptions compressOptions = new LubanOptions.Builder().setMaxSize(compress.getSizeLimit())
//                                .setUnit(compress.getUnit()).create();
//                        CompressOptions config = CompressOptions.ofLuban(compressOptions);
                        LubanOptions.Builder builder = new LubanOptions.Builder();
                        if (maxSize != null) {
                            if (maxSize != null && !TextUtils.isEmpty(maxSize.getWidth()) && !TextUtils.isEmpty(maxSize.getHeight())) {

                                builder.setMaxWidth(Integer.parseInt(maxSize.getWidth()));

                                builder.setMaxHeight(Integer.parseInt(maxSize.getHeight()));
                            }
                        }
                        if (compress != null) {
                            builder.setMaxSize(compress.getSizeLimit() * 1024).setUnit(compress.getUnit());
                        }
                        LubanOptions compressOptions = builder.create();

                        CompressOptions config = CompressOptions.ofLuban(compressOptions);
                        getTakePhoto().onEnableCompress(config, true);
                    } else {
                        getTakePhoto().onEnableCompress(null, false);
                    }

                    int limit = photo.getMaxNum();
                    if (limit > 1) {
                        Crop crop = photo.getCrop();
                        if (crop != null) {
                            LogUtils.d(" crop mulitule pictures with width: " + crop.getWidthRatio() + " height:" + crop.getHeightRatio() + " format:" + photo.getFormat());
                            CropOptions.Builder cropBuilder = new CropOptions.Builder();
                            CropOptions cropOptions = cropBuilder.setAspectX(crop.getWidthRatio()).setAspectY(crop.getHeightRatio()).setFormat(photo.getFormat()).create();
                            takePhoto.onPickMultipleWithCrop(limit, cropOptions);

                        } else {
                            getTakePhoto().onPickMultiple(limit);
                        }

                    } else {

                        Crop crop = photo.getCrop();
                        if (crop != null) {
                            LogUtils.d(" crop one picture with width: " + crop.getWidthRatio() + " height:" + crop.getHeightRatio() + " format:" + photo.getFormat());
                            CropOptions.Builder cropBuilder = new CropOptions.Builder();
                            CropOptions cropOptions = cropBuilder.setOutputX(crop.getWidthRatio()).setOutputY(crop.getHeightRatio()).setFormat(photo.getFormat()).create();
                            takePhoto.onPickFromGalleryWithCrop(imageUri, cropOptions);
                        } else {
                            takePhoto.onPickFromGallery();
                        }
                    }


                }
                apiName = "selectPicture";
                selectPictureCallBackFunction = function;
            }
        });

        /**
         * 保存图片
         */
        webview.registerHandler("savePicture", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

                if (TextUtils.isEmpty(data)) {
                    return;
                }
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("url") != null) {
                    String url = jsonObject.get("url").getAsString() + "";
                    savePictureCallBackFunction = function;
                    if (!TextUtils.isEmpty(url)) {
                        saveImage(url);
                    }

                    apiName = "savePicture";


                }
            }

        });

        webview.registerHandler("scan", new BridgeHandler() {
            @Override
            public void handler(final String data, final CallBackFunction function) {
                LogUtils.d("---- h5 scan");
                if (TextUtils.isEmpty(data)) {
                    return;
                }

                scanCallBackFunction = function;
                XXPermissions.with(H5BridgeActivity.this).permission(Permission.CAMERA
                ).request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        dismissTopDialog();
                        Intent intent = new Intent(H5BridgeActivity.this, ScanActivity.class);

                        JsonObject jsonObject = HostJsScope.Json2JsonObject(data);

                        if (jsonObject != null && jsonObject.get("title") != null) {
                            String title = jsonObject.get("title").getAsString() + "";
                            intent.putExtra("title", title);
                        }
                        if (jsonObject != null && jsonObject.get("text") != null) {
                            String title = jsonObject.get("text").getAsString() + "";
                            intent.putExtra("text", title);
                        }
                        intent.putExtra("from", "H5BridgeActivity");


                        startActivityForResult(intent, 5);

                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        dismissTopDialog();
                        HostJsScope.h5PostLocalCallBack(webview, "11", "未开启摄像头权限", false, "scan", null, scanCallBackFunction);

                    }
                });
                if (!XXPermissions.isHasPermission(H5BridgeActivity.this, Permission.CAMERA)) {
                    showTopDialog("为了您能正常使用【扫码】功能，需向您申请相机权限。如果不允许，您将无法使用扫码功能。");
                }

            }

        });

        webview.registerHandler("authV2", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                authV2CallBackFunction = function;
                getSign();
            }
        });


        webview.registerHandler("tradePay", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                payV2CallBackFunction = function;

//                入参 payType：’alipay’/‘weixin'  //预留微信支付
//                orderInfo：’xxxxxxxxxx’   //服务端返回的订单信息+签名
//                Log.e("lkf", "" + data);
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("payType") != null) {
                    String payType = jsonObject.get("payType").getAsString() + "";

                    String orderInfo = jsonObject.get("orderInfo").getAsString() + "";
//                    Log.e("lkf", "" + orderInfo);
                    if ("alipay".equals(payType)) {

                        payV2(orderInfo);
                    }

                }

            }
        });


        /**
         * 图片缩放预览
         */
        webview.registerHandler("viewPicture", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

                Image image = (Image) GsonUtils.json2Obj(data, Image.class);
                if (image != null) {
                    Intent intent = new Intent(H5BridgeActivity.this, PhotoViewActivity.class);
                    intent.putExtra("currentIndex", image.getCurrent());

                    intent.putStringArrayListExtra("files", image.getFiles());
                    startActivity(intent);
                    apiName = "viewPicture";
                    photoviewCallBackFunction = function;
                }
            }
        });

        /**
         * 上传文件及参数
         */
        webview.registerHandler("uploadPicture", new BridgeHandler() {
            @Override
            public void handler(String data, final CallBackFunction function) {
                LogUtils.d("upload data==== " + data);
                final Upload upload = (Upload) GsonUtils.json2Obj(data, Upload.class);
                if (upload != null) {
                    if (!TextUtils.isEmpty(upload.getUrl())) {
                        uploadPictureCallBackFunction = function;
                        XXPermissions.with(H5BridgeActivity.this).permission(Permission.WRITE_EXTERNAL_STORAGE,
                                Permission.READ_EXTERNAL_STORAGE).request(new OnPermission() {

                            @Override
                            public void hasPermission(List<String> granted, boolean isAll) {
                                if (isAll) {
                                    dismissTopDialog();
                                    TUtils.uploadPictures(webview, upload.getUrl(), upload.getFile(), upload.getData());
                                    apiName = "uploadPicture";

                                }
                            }

                            @Override
                            public void noPermission(List<String> denied, boolean quick) {
                                dismissTopDialog();
                                HostJsScope.h5PostLocalCallBack(webview, "-1", "未开启存储权限", false, "uploadPicture", "", uploadPictureCallBackFunction);
                                if (uploadPictureCallBackFunction != null) {
                                    uploadPictureCallBackFunction = null;
                                }
                            }
                        });
                        if (!XXPermissions.isHasPermission(H5BridgeActivity.this, Permission.WRITE_EXTERNAL_STORAGE,
                                Permission.READ_EXTERNAL_STORAGE)) {
                            showTopDialog("为了您能正常上传身份证，完成身份认证等功能，，需向您申请媒体文件存储权限。如果不允许，您将无法存储和取用相册图片。");
                        }

                    }
                }
            }
        });

    }

    private void saveImage(final String imgUrl) {
        XXPermissions.with(this).permission(Permission.WRITE_EXTERNAL_STORAGE,
                Permission.READ_EXTERNAL_STORAGE).request(new OnPermission() {

            @Override
            public void hasPermission(List<String> granted, boolean isAll) {
                if (isAll) {
                    dismissTopDialog();
                    new H5BridgeActivity.WriteString(imgUrl).start();
                }
            }

            @Override
            public void noPermission(List<String> denied, boolean quick) {
                Response_Base response_base = new Response_Base();
                response_base.setResultObject(null);
                response_base.setCode("-1");
                response_base.setSuccess(false);
                HostJsScope.h5PostLocalCallBack(webview, "-1", "未开启存储权限", false, "savePicture", response_base, savePictureCallBackFunction);

            }
        });
        if (!XXPermissions.isHasPermission(H5BridgeActivity.this, Permission.WRITE_EXTERNAL_STORAGE,
                Permission.READ_EXTERNAL_STORAGE)) {
            showTopDialog("为了您能正常使用【保存图片】等功能，，需向您申请媒体文件存储权限。如果不允许，您将无法存储和取用相册图片。");
        }

    }

    private class WriteString extends Thread {

        private String url;

        public WriteString(String url) {
            this.url = url;
        }

        @Override
        public void run() {
            super.run();
            //干你需要做的操作
            String fileUrl = FileUtils.writeFile(url);
            Response_Base response_base = new Response_Base();
            response_base.setResultObject(null);
            if (!TextUtils.isEmpty(fileUrl)) {
                response_base.setCode("0");
                response_base.setSuccess(true);
                HostJsScope.h5PostLocalCallBack(webview, "0", "", true, "savePicture", response_base, savePictureCallBackFunction);

                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.fromFile(new File(fileUrl));
                intent.setData(uri);
                sendBroadcast(intent);
            } else {
                response_base.setCode("-1");
                response_base.setSuccess(false);
                HostJsScope.h5PostLocalCallBack(webview, "-1", "", false, "savePicture", response_base, savePictureCallBackFunction);
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 5 && resultCode == 5) {
            if (data != null) {
                String code = data.getStringExtra("code");
                if (!TextUtils.isEmpty(code)) {

//                    result: {error, barCode, qrCode, cardNumber}错误码（10： 用户取消， 11： 操作失败）
                    HostJsScope.h5PostLocalCallBack(webview, "0", "", true, "scan", code, scanCallBackFunction);
                } else {

                    if (!TextUtils.isEmpty(data.getStringExtra("cancel"))) {

                        HostJsScope.h5PostLocalCallBack(webview, "10", "", false, "scan", null, scanCallBackFunction);

                    } else {

                        HostJsScope.h5PostLocalCallBack(webview, "11", "", false, "scan", null, scanCallBackFunction);

                    }
//                    result: {error, barCode, qrCode, cardNumber}错误码（10： 用户取消， 11： 操作失败）

                }

            }
        } else {
            getTakePhoto().onActivityResult(requestCode, resultCode, data);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void takeSuccess(TResult result) {
        if (result != null) {
            /**
             * 拍照裁剪图片返回数据
             */
            if (takePictureCallBackFunction != null) {
                TImage image = result.getImage();
                if (image != null) {

                    String imagePath = image.getCompressPath();
                    if (TextUtils.isEmpty(imagePath)) {
                        imagePath = image.getOriginalPath();
                    }

                    if (!TextUtils.isEmpty(imagePath)) {
                        HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_SUCCESS, "成功", true, apiName, "file://" + imagePath, takePictureCallBackFunction);
                        takePictureCallBackFunction = null;
                    }
                }
            }

            /**
             * 选择图片裁剪返回数据
             */
            if (selectPictureCallBackFunction != null) {
                List<TImage> images = result.getImages();

                List<String> imagePaths = new ArrayList<>();
                if (images != null && images.size() > 0) {
                    for (TImage tImage : images) {
                        if (tImage != null) {
                            String imagePath = tImage.getCompressPath();
                            if (TextUtils.isEmpty(imagePath)) {
                                imagePath = tImage.getOriginalPath();
                            }

                            imagePaths.add("file://" + imagePath);
                            LogUtils.d(" images ==== " + imagePath);
                        }
                    }
                    if (imagePaths != null && imagePaths.size() > 0) {
                        HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_SUCCESS, "成功", true, apiName, imagePaths, selectPictureCallBackFunction);
                        selectPictureCallBackFunction = null;
                    }
                }

            }
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {
        if (takePictureCallBackFunction != null) {
            HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL, "失败", true, apiName, "", takePictureCallBackFunction);
            takePictureCallBackFunction = null;
        }
        if (selectPictureCallBackFunction != null) {
            HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL, "失败", true, apiName, "", selectPictureCallBackFunction);
            selectPictureCallBackFunction = null;
        }

    }

    @Override
    public void takeCancel() {

        if (takePictureCallBackFunction != null) {
            //HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_CANCEL, "取消", true, apiName, "", takePictureCallBackFunction);
            takePictureCallBackFunction = null;
        }
        if (selectPictureCallBackFunction != null) {
            //HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_CANCEL, "取消", true, apiName, "", selectPictureCallBackFunction);
            selectPictureCallBackFunction = null;
        }
    }

    /**
     * 自定义的WebViewClient
     */
    class MyWebViewClient extends BridgeWebViewClient {

        public MyWebViewClient(BridgeWebView webView) {
            super(webView);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
//            showLoadingNoCancelable("正在载入...");
//            showLoading("正在载入...");
            Log.i("lkf", " onPageStarted----");
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (!isErrorPage) {
                hideErrorPage();
            }


            view.loadUrl("javascript:window.YzJSBridge = window.WebViewJavascriptBridge;window.YzJSBridge.call = window.YzJSBridge.callHandler;");
            view.loadUrl("javascript:AppUtil.trigger(AppUtil.EVENTS.READY_EVENT);");
            view.loadUrl("javascript:readyFunc();");
            loading_layout.setVisibility(View.GONE);
//            Log.i("lkf", " onPageFinished----" + url + "---------------------");
            dismissLoading();

        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            Log.i("zx", failingUrl + "onReceivedError==" + description + "     errorCode" + errorCode);
            showErrorPage();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.i("lkf", " shouldOverrideUrlLoading----");
            if (url.startsWith("taobao://")) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
                //此处需要关闭新窗口视图
//                onBackPressed();

                return true;
            }
            if (url.trim().startsWith("tel")) {//特殊情况tel，调用系统的拨号软件拨号【<a href="tel:1111111111">1111111111</a>】
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(url));
                startActivity(i);
            }


            return super.shouldOverrideUrlLoading(view, url);

        }

    }

    private boolean isErrorPage;//默认false 说明不是错误页面

    public void showErrorPage() {
        errorLayout.setVisibility(View.VISIBLE);
        webview.setVisibility(View.GONE);
        isErrorPage = true;
    }

    public void hideErrorPage() {
        errorLayout.setVisibility(View.GONE);
        webview.setVisibility(View.VISIBLE);
    }

    public void payV2(final String orderInfo) {
        if (!TextUtils.isEmpty(orderInfo)) {

            Runnable payRunnable = new Runnable() {

                @Override
                public void run() {
                    PayTask alipay = new PayTask(H5BridgeActivity.this);
                    Map<String, String> result = alipay.payV2(orderInfo, true);
                    Log.i("msp", result.toString());

                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }
            };

            Thread payThread = new Thread(payRunnable);
            payThread.start();

        } else {
            HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL, "未获取到orderInfo", true,
                    "tradePay", "", payV2CallBackFunction);
            if (payV2CallBackFunction != null) {
                payV2CallBackFunction = null;
            }
        }

    }

    /**
     * 获取sign 并且支付宝登录
     */
    private void getSign() {
        showLoading("正在加载...");
        NetWorkRequset.doJoinLogin(new MySubscriber() {
            @Override
            public void onSuccess(Response_Base response_baseModel) {
                dismissLoading();
                String sign = (String) response_baseModel.getResultObject();
                if (!TextUtils.isEmpty(sign)) {
                    authV2(sign);
                } else {
//                    showToast("未获取到sign");
                    HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL, "未获取到sign", true, "authV2", "", authV2CallBackFunction);
                    if (authV2CallBackFunction != null) {
                        authV2CallBackFunction = null;
                    }
                }
            }

            @Override
            public void onNeedLogin(String msg) {
                dismissLoading();

            }

            @Override
            public void onCompleted() {
                super.onCompleted();
                dismissLoading();

            }

            @Override
            public void onFail(Response_Base response_baseModel) {
                dismissLoading();
                if (!TextUtils.isEmpty(response_baseModel.getMsg())) {
                    HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL, response_baseModel.getMsg(), true, "authV2", "", authV2CallBackFunction);
                    if (authV2CallBackFunction != null) {
                        authV2CallBackFunction = null;
                    }
                    // showToast(response_baseModel.getMsg());
                }
            }
        });
    }

    /**
     * 支付宝账户授权业务
     */
    private void authV2(final String sign) {
        Runnable authRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造AuthTask 对象
                AuthTask authTask = new AuthTask(H5BridgeActivity.this);
                // 调用授权接口，获取授权结果
                Map<String, String> result = authTask.authV2(sign, true);

                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread authThread = new Thread(authRunnable);
        authThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
//                    Log.e("lkf", payResult.toString());
                    HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_SUCCESS, "", true,
                            "tradePay", payResult, payV2CallBackFunction);
                    if (payV2CallBackFunction != null) {
                        payV2CallBackFunction = null;
                    }
                    break;
                }
                case 1: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();
                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
//                        Response_Base response_base = new Response_Base();
//                        response_base.setCode("0");
//                        response_base.setSuccess(true);
//                        response_base.setResultObject(authResult.getUserId());
                        HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_SUCCESS, "", true, "authV2", authResult.getUserId(), authV2CallBackFunction);
                    } else {
                        // 其他状态值则为授权失败
//                        Toast.makeText(H5BridgeOtherActivity.this, "授权失败", Toast.LENGTH_SHORT).show();
                        HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL, "授权失败", true, "authV2", "", authV2CallBackFunction);
                    }
                    if (authV2CallBackFunction != null) {
                        authV2CallBackFunction = null;
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    public void showVersionUpdate(AppVersion appVersion, final String url) {
        LogUtils.e("=== showVersionUpdate - appVersion: " + appVersion.getVersion() + " url: " + url);
        Intent intentDown = new Intent(this, DownLoadDialogActivity.class);
        intentDown.putExtra("url", url);
        intentDown.putExtra("autoLogin", "H5Bridge");
        intentDown.putExtra("appVersion", appVersion);
        startActivity(intentDown);

    }


    //未授权权限弹出对话框
    public void permissionDialog(String msg) {
        final PublicDialog permission = new PublicDialog(H5BridgeActivity.this);
        permission.setTitle("请开启相关权限");
        permission.setMessage(msg);
        permission.setRightBtn("去设置", new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                XXPermissions.gotoPermissionSettings(H5BridgeActivity.this);
                permission.dismiss();
            }
        });
        permission.setLeftBtn("取消", new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                permission.dismiss();
                H5BridgeActivity.this.finish();
            }
        });
        permission.setCancelable(false);
        permission.show();

    }

    private TopDialog topDialog = null;

    public void showTopDialog(String content) {
        topDialog = new TopDialog(this);
        topDialog.setContent(content);
        topDialog.show();
    }

    private void dismissTopDialog() {
        if (topDialog != null) {
            topDialog.dismiss();
            topDialog = null;
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        startService(new Intent(this, PlayerMusicService.class));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (smartConfig != null) {
            smartConfig.stop();
        }
        if (webview != null) {
            webview.destroy();
        }
        if (myRecriver != null) {
            unregisterReceiver(myRecriver);
        }
    }
}
